<?php

/**
 * @author  Samuel Carlier
 * @package P3Base_Mailer
 */
class P3Base_Mailer_Files {

	/**
	 * @var array
	 */
	private $_files = array();

	/**
	 * read comment about the auto option for
	 * $force_mime_type at getMimeType method
	 * 
	 * @param string $file_path
	 * @param string $newname
	 * @param string $force_mime_type
	 */
	public function add($file_path, $newname, $force_mime_type=null) {
		if(empty($newname)) {
			$newname = basename($file_path);
		}

		if($force_mime_type == 'auto') {
			$force_mime_type = $this->_getMimeType($newname);
		}

		$content_id = 'P3Mailer@' . md5($newname . '_' . microtime());
		$this->_files[] = array('content_id' => $content_id,
								'path' => $file_path, 
								'name' => $newname,
								'force_mime' => $force_mime_type);
	}

	/**
	 * delete all added files
	 */
	public function clear() {
		$this->_files = array();	
	}
	
	/**
	 * @return array
	 */
	public function get() {
		return $this->_files;	
	}
	
	/**
	 * @return int
	 */
	public function count() {
		return count($this->_files);	
	}

	/**
	 * @param string $iteratorName 	mail
	 *
	 * @return Iterator
	 */
	public function getIterator($iteratorName='mail') {
		$iteratorName = strtolower($iteratorName);

		switch($iteratorName) {
			case 'mail':
				$iterator = new P3Base_Mailer_Iterator_MailFile($this->get());
			break;	

			default:
				throw new P3Base_Mailer_Exception('unsupported iterator: "'.$iteratorName.'"');
		}

		return $iterator;
	}
	
	/**
	 * Function currenty only used for images (created for inline images)
	 * dont know yet if i will use a mime read extension.
	 * 
	 * @param  string $filename
	 * @return string
	 */
	private function _getMimeType($filename) {
		$extension = substr($filename, strrpos($filename, '.') + 1);

		switch($extension) {
			case 'jpg':
			case 'jpe':
			case 'jpeg':
				$mime = 'image/jpeg';
				break;

			case 'gif':
				$mime = 'image/gif';
				break;
				
			case 'png':
				$mime = 'image/png';
				break;
				
			default:
				throw new P3Base_Mailer_Exception('Unsupported inline image with extension: ' . $extension);
		}
		
		return $mime;
	}
}

?>